import logging
import os
from typing import Annotated

from sqlalchemy.ext.asyncio import AsyncSession
from fastapi.security.api_key import APIKey
from fastapi import APIRouter, status, Depends, Path
from fastapi.responses import JSONResponse
import base64

from utils.file_support import load_image_file
from . import schemas
from . import crud
from price_analysis.core.models import aux_db_helper
from price_analysis.core.config import settings
from price_analysis.auth import auth
from price_analysis.utils.data_processing import search_data_in_FSSC2020
from price_analysis.utils.search_online import SearchOnline
from price_analysis.api_v1.recognize_so.crud import get_all_recognized_data

logger = logging.getLogger("main")

router = APIRouter(tags=["processing_data"])


@router.post(
    "/",
    status_code=status.HTTP_200_OK,
)
async def processing_get_command(
    command: schemas.ProcessCommand,
    api_key: APIKey = Depends(auth.get_api_key),
    session: AsyncSession = Depends(aux_db_helper.get_async_session),
) -> dict:
    logger.info(f"получена команда {command.command} {command.data}")

    match command.command:
        case "SEARCH-IN-FSSC":
            data: list[dict] = await get_all_recognized_data()
            await search_data_in_FSSC2020(data, session)

        case "SEARCH-ONLINE":
            data: list[dict] = await crud.get_data_for_search_online()
            search_online = SearchOnline()
            await search_online.get_price_and_images(data=data)

        case _:
            return {"result": "error"}

    return {"result": "success"}


@router.get(
    "/get-in-fssc/",
    status_code=status.HTTP_200_OK,
)
async def get_data_in_fssc(
    api_key: APIKey = Depends(auth.get_api_key),
) -> list[dict]:
    filename: str = os.path.join(settings.ocr_data_path, "in_fssc" + ".json")
    return await crud.get_all_in_fssc(filename=filename)


@router.delete(
    "/get-in-fssc/{idx}/",
    status_code=status.HTTP_200_OK,
)
async def delete_item_from_in_fssc(
    idx: Annotated[int, Path()],
    api_key: APIKey = Depends(auth.get_api_key),
) -> list[dict]:
    return await crud.delete_item_in_fssc(idx)


@router.get(
    "/get-from-online/",
    status_code=status.HTTP_200_OK,
)
async def get_data_from_online(
    api_key: APIKey = Depends(auth.get_api_key),
):
    return await crud.get_search_online_result()


@router.post(
    "/image/",
    response_class=JSONResponse,
    status_code=status.HTTP_200_OK,
)
async def get_images(
    file_path: schemas.ImagePath,
    api_key: APIKey = Depends(auth.get_api_key),
):
    image = await load_image_file(file_path.path)
    base64_encoded = base64.b64encode(image).decode("utf-8")

    return {"image": f"data:image/png;base64,{base64_encoded}"}


@router.delete(
    "/image/{idx}",
    status_code=status.HTTP_200_OK,
)
async def delete_offer(
    idx: Annotated[int, Path()],
    api_key: APIKey = Depends(auth.get_api_key),
):
    return await crud.delete_offer(idx)
